package com.zrj.auth.config;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.zrj.auth.constant.RedisConstants;
import com.zrj.auth.core.enhancer.JwtTokenEnhancer;
import com.zrj.auth.core.extensions.mobile.SmsCodeTokenGranter;
import com.zrj.auth.core.extensions.wechat.WechatTokenGranter;
import com.zrj.auth.core.userdetails.user.SysUserDetailsServiceImpl;
import com.zrj.auth.pojo.response.ResultCode;
import com.zrj.auth.pojo.response.Results;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.sql.DataSource;
import java.security.KeyPair;
import java.util.*;

/**
 * 认证授权配置
 * @author zhaorujie
 */
@Configuration
@RequiredArgsConstructor
@Slf4j
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    //private final ClientDetailsServiceImpl clientDetailsService;
    private final AuthenticationManager authenticationManager;
    private final RedisConnectionFactory redisConnectionFactory;
    private final JwtTokenEnhancer jwtTokenEnhancer;
    private final SysUserDetailsServiceImpl sysUserDetailsService;
    private final DataSource dataSource;

    /**
     * 令牌端点安全约束配置
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //表示支持client_id，client_secret的表单方式登录
                .allowFormAuthenticationForClients();
    }

    /**
     * 采用jdbc的方式获取客户端信息
     * @return
     */
    @Bean
    public ClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 客户端详情配置
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetails());
        //自定义的客户端获取方式
        //clients.withClientDetails(clientDetailsService);
    }

    /**
     * 令牌访问端点配置
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //Token增强
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
        //添加jwt内容增强
        tokenEnhancers.add(jwtTokenEnhancer);
        //对令牌进行增强为jwt令牌
        tokenEnhancers.add(jwtAccessTokenConverter());
        tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);
        //授权模式
        List<TokenGranter> granterList = new ArrayList<>(Arrays.asList(endpoints.getTokenGranter()));
        //添加手机短信验证码授权模式的授权者
        granterList.add(new SmsCodeTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),
                endpoints.getOAuth2RequestFactory(), authenticationManager));
        //添加微信小程序员授权模式的授权者
        granterList.add(new WechatTokenGranter(endpoints.getTokenServices(),endpoints.getClientDetailsService(),
                endpoints.getOAuth2RequestFactory(), authenticationManager));
        CompositeTokenGranter compositeTokenGranter = new CompositeTokenGranter(granterList);
        endpoints
                //密码模式所需要的authenticationManager
                .authenticationManager(authenticationManager)
                //添加授权码模式所需要的authorizationCodeServices
                .authorizationCodeServices(authorizationCodeServices())
                //.userDetailsService(sysUserDetailsService)
                .accessTokenConverter(jwtAccessTokenConverter())
                //token增强
                .tokenEnhancer(tokenEnhancerChain)
                //授权模式
                .tokenGranter(compositeTokenGranter)
                //令牌管理服务
                .tokenServices(tokenServices(endpoints));
    }

    /**
     * 令牌管理服务配置
     * @param endpoints
     * @return
     */
    public DefaultTokenServices tokenServices(AuthorizationServerEndpointsConfigurer endpoints) {
        //Token增强
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
        tokenEnhancers.add(jwtTokenEnhancer);
        tokenEnhancers.add(jwtAccessTokenConverter());
        tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);

        DefaultTokenServices tokenServices = new DefaultTokenServices();
        //用reids存储token
        //tokenServices.setTokenStore(tokenStore());
        tokenServices.setTokenStore(endpoints.getTokenStore());
        tokenServices.setSupportRefreshToken(true);
        //设置jdbc获取客户端方式
        //tokenServices.setClientDetailsService(clientDetailsService);
        tokenServices.setClientDetailsService(clientDetails());
        tokenServices.setTokenEnhancer(tokenEnhancerChain);

        tokenServices.setReuseRefreshToken(true);
        return tokenServices;
    }

    /**
     * 令牌存储策略配置
     * @return
     */
    @Bean
    public TokenStore tokenStore() {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        redisTokenStore.setPrefix(RedisConstants.AUTH_ACCESS);
        return redisTokenStore;
    }

    /**
     * 授权码模式的service，使用authorization_code必须注入
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    /**
     * 使用非对称加密算法对token签名
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyPair());
        return converter;
    }

    /**
     * 密钥库中获取密钥对(公钥+私钥)
     */
    @Bean
    public KeyPair keyPair() {
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
        return factory.getKeyPair("jwt", "123456".toCharArray());
    }

    /**
     * 自定义认证异常响应数据
     * @return
     */
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, e) -> {
            response.setStatus(HttpStatus.HTTP_OK);
            response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control", "no-cache");
            Results<Object> result = Results.failed(ResultCode.CLIENT_AUTHENTICATION_FAILED);
            response.getWriter().print(JSONUtil.toJsonStr(result));
            response.getWriter().flush();
        };
    }
}
